<?php
namespace app\components\printMachine\feie;

use app\components\printMachine\feie\formatter\Formatter;
use app\components\printMachine\feie\formatter\Type58;
use app\components\printMachine\feie\formatter\Type80;
use app\components\printMachine\ProviderInterface;
use app\utils\HttpUtil;
use yii\base\UserException;

class FeieProvider implements ProviderInterface {

    //打印机API网关
    const URL = "http://api.feieyun.cn/Api/Open/";

    private static $formatter = [
        '1'=>Type58::class,
        '2'=>Type80::class
    ];

    /**
     * @var Formatter[] $_formatter
     */
    private $_formatter = [];

    public function __construct($type)
    {
        if(!array_key_exists($type,self::$formatter)){
            throw new UserException(\Yii::t("app","格式化类型不支持"));
        }
    }

    protected function getFormatter($type) : Formatter {
        if(array_key_exists(self::$formatter[$type],$this->_formatter)){
            return $this->_formatter[self::$formatter[$type]];
        }
        $this->_formatter[self::$formatter[$type]] = new self::$formatter[$type]();
        return $this->_formatter[self::$formatter[$type]];
    }

    public function print($header,$arr,$sn,$type,$count)
    {
        $str = $this->getFormatter($type)->format($header,$arr);

        $time = time();
        $data = [
            'user'=>\Yii::$app->params['print']['feie']['user'],
            'stime'=>$time,
            'sig'=>sha1(\Yii::$app->params['print']['feie']['user'] . \Yii::$app->params['print']['feie']['key'].$time),
            'apiname'=>'Open_printMsg',
            'sn'=>$sn,
            'content'=>$str,
            'times'=>$count
        ];

        $result = HttpUtil::request(self::URL,HttpUtil::METHOD_POST,$data,HttpUtil::FORMAT_URLENCODED);
        if($result['ret'] != 0){
            \Yii::info($result['msg']);
            return false;
        }
        return true;
    }
}